<?php

namespace App\Models;

use App\Handlers\HtmlHandler;
use App\Handlers\KeysHandler;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Article extends Model
{
    use HasDateTimeFormatter;

    const HELP_CENTER = 'HelpCenter';//帮助中心
    //const PURCHASE_WITHDRAWAL = 'PurchaseWithdrawal';//如何购买和提款
    //const TASK_INVITATION = 'TaskInvitation';//任务详情邀请文案

    const ARTICLE_OPTIONS = [
        self::HELP_CENTER => '常见问题',
        //self::TEAM => '团队介绍',
        //self::ABOUT_US => '关于我们',
        //self::GAME_HELP => '游戏介绍',
        //self::PURCHASE_WITHDRAWAL => '如何购买和提款',
        //self::TASK_INVITATION => '任务详情邀请文案',
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'key', 'title', 'image', 'content', 'page_views', 'sort', 'created_at', 'updated_at'
    ];

    public function getLocaleAttribute($value)
    {
        return explode(',', $value);
    }

    public function setLocaleAttribute($value)
    {
        $this->attributes['locale'] = implode(',', $value);
    }

    public static function getByKey($key)
    {
        $_key = sprintf(KeysHandler::ARTICLE, $key);

        $article = Cache::get($_key);
        if (!$article) {
            $article = self::where('key', '=', $key)->first();
            $article ? Cache::put($_key, $article, 60 * 60 * 24) : Cache::put($_key, '', 60);
        }
        if (isset($article['content'])) {
            $article['content'] = HtmlHandler::makeContent($article['content']);
        }
        if (!empty($article) && !empty($article['id'])) {
            self::query()->where('id', $article['id'])->increment('page_views', rand(10, 99));
        }
        return $article;
    }
}
